package com.woniu.shop.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.faceid.v20180301.models.IdCardOCRVerificationResponse;
import com.tencentcloudapi.ocr.v20181119.models.VerifyBasicBizLicenseResponse;
import com.woniu.Result;
import com.woniu.shop.utils.IdCardOCRVerification;
import com.woniu.shop.utils.QiNiuUploadUtils;
import com.woniu.shop.utils.VerifyBasicBizLicense;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/upload")
@Api(tags = "图片上传管理")
public class UploadController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(@RequestPart MultipartFile file) throws IOException {
        // 1. 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2. 重新设置文件的名称
        String uuid = UUID.randomUUID().toString();
        // 文件的名称 = uuid + 源文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid + substring;
        fileName = fileName.replaceAll("-", "");
        stringRedisTemplate.opsForSet().add("redis_all_upload_image",fileName);
        log.debug("文件名称为： {}",fileName);
        // 3. 调用图片上传的工具类
        QiNiuUploadUtils.uploadFile(file.getBytes(), fileName);
        // 4. 响应数据
//        return toDataResult(fileName);
        return Result.ok(fileName);
    }

    @ApiOperation("删除图片")
    @GetMapping("/delete")
    public Result<String> delete(String fileName){
        QiNiuUploadUtils.deleteFile(fileName);
        return Result.ok();
    }

    @ApiOperation("身份证图片路径验证")
    @GetMapping("/idCard/{imagName}")
    public Result<IdCardOCRVerificationResponse> IDCard(@PathVariable String imagName) throws TencentCloudSDKException {
        String imageUrl = "http://rlfk0nlhy.hn-bkt.clouddn.com/" + imagName;
        IdCardOCRVerificationResponse response = IdCardOCRVerification.IdCardVerification(imageUrl);
        return Result.ok(response);

    }

    @ApiOperation("营业执照图片路径验证")
    @GetMapping("/basicBiz/{imagName}")
    public Result<VerifyBasicBizLicenseResponse> bizLicense(@PathVariable String imagName){
        String imageUrl = "http://rlfk0nlhy.hn-bkt.clouddn.com/" + imagName;
        VerifyBasicBizLicenseResponse verifyBizLicense = VerifyBasicBizLicense.verifyBizLicense(imageUrl);

        return Result.ok(verifyBizLicense);
    }
}
